package com.ssm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ssm.service.DonghuaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author lvshiwei
 * @description 东华监测业务类
 * @date 2021-10-12
 */
@Service
@Slf4j
public class DonghuaServiceImpl implements DonghuaService {

    //引入mongodb API
    @Autowired
    private MongoTemplate mongoTemplate;
    //引入远程http服务
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 录入监测数据到mongodb
     * @param jstr json字符串
     * @param content 原报文
     */
    @Override
    public void insert(String jstr, String content) {
        if (StringUtils.isBlank(jstr)) {
            return;
        }
        //将json字符串转成json对象
        JSONObject json = JSONObject.parseObject(jstr);
        //过滤无效数据
        if ("3020".equals(json.getString("CN"))) {
            return;
        }
        //录入监测数据对象
        JSONObject res = mongoTemplate.save(json, "juguang");
        log.info("录入聚光数据对象为: {}", res.toJSONString());
        //向suzhouwater工程投放报文,以便对接三标
        JSONObject req = new JSONObject();
        req.put("content", content);
        String lstr = restTemplate.postForObject("http://112.126.97.123:8080/suzhou_water-1.0-SNAPSHOT/logs/insertLogs",
                req, String.class);
        JSONObject ljson = JSONObject.parseObject(lstr);
        if (null == ljson || 200 != ljson.getIntValue("code")) {
            log.error("向suzhou_water工程投放错误!");
        }
    }
}
